package org.jim.server.command.handler;

import java.util.Objects;

import org.jim.core.ImChannelContext;
import org.jim.core.ImPacket;
import org.jim.core.ImStatus;
import org.jim.core.exception.ImException;
import org.jim.core.packets.AuthReqBody;
import org.jim.core.packets.AuthUserRespBody;
import org.jim.core.packets.Command;
import org.jim.core.packets.RespBody;
import org.jim.core.utils.JsonKit;
import org.jim.server.JimServerAPI;
import org.jim.server.command.AbstractCmdHandler;
import org.jim.server.processor.login.AuthCmdProcessor;
import org.jim.server.protocol.ProtocolManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 
 * 版本: [1.0]
 * 功能说明: 鉴权请求消息命令处理器
 * @author : WChao 创建时间: 2017年9月13日 下午1:39:35
 */
public class AuthReqHandler extends AbstractCmdHandler
{
	private static Logger log = LoggerFactory.getLogger(AuthReqHandler.class);

	@Override
	public ImPacket handler(ImPacket packet, ImChannelContext channelContext) throws ImException
	{
		
		if (packet.getBody() == null) {
			RespBody respBody = new RespBody(Command.COMMAND_AUTH_RESP,ImStatus.C10010);
			return ProtocolManager.Converter.respPacket(respBody, channelContext);
		}
		//自己的业务
		AuthCmdProcessor authProcessor = this.getSingleProcessor(AuthCmdProcessor.class);
		//需要自己处理的时候
		if(Objects.nonNull(authProcessor)){
			AuthReqBody authReqBody = JsonKit.toBean(packet.getBody(),AuthReqBody.class);
			//ImPacket respPacket = ProtocolManager.Converter.respPacket(authReqBody, channelContext);
			//去鉴权
			AuthUserRespBody respBody = authProcessor.doAuth(authReqBody, channelContext);
			if (Objects.isNull(respBody) || respBody.getCode() != ImStatus.C10009.getCode()) {
				log.error("login failed, token:{}", authReqBody.getToken());
				authProcessor.onFailed(channelContext);
				JimServerAPI.bSend(channelContext, ProtocolManager.Converter.respPacket(respBody, channelContext));
				JimServerAPI.remove(channelContext, "userId or token is incorrect");
				return null;
			}
			
			//去拿用户信息并绑定
			authProcessor.onSuccess(respBody.getUser(),channelContext);
			//返回信息
			return ProtocolManager.Converter.respPacket(respBody, channelContext);
		}
		
//		AuthReqBody authReqBody = JsonKit.toBean(packet.getBody(), AuthReqBody.class);
//		String token = authReqBody.getToken() == null ? "" : authReqBody.getToken();
//		String data = token +  ImConst.AUTH_KEY;
//		authReqBody.setToken(data);
//		authReqBody.setCmd(null);
		RespBody respBody = new RespBody(Command.COMMAND_AUTH_RESP,ImStatus.C10010);
		return ProtocolManager.Converter.respPacket(respBody, channelContext);
	}

	@Override
	public Command command() {
		return Command.COMMAND_AUTH_REQ;
	}
}
